<template>
  <sec-popover
    placement="bottom-end"
    trigger="click"
    :visible-arrow="false"
    popper-class="event-operate-column"
  >
    <div class="container">
      <sec-tree
        :data="tableColumn"
        :props="defaultProps"
        show-checkbox
        node-key="prop"
        :default-checked-keys="defaultChecked"
        @check="nodeCheck"
      ></sec-tree>
    </div>
    <sec-button slot="reference" icon="sec-icon-shezhi"></sec-button>
  </sec-popover>
</template>

<script>
import filter from 'lodash/filter'
import { mapState } from 'vuex'
export default {
  components: {},
  props: {
    defaultTableColumn: {
      type: Array,
      default: () => {
        return []
      }
    },
    columnKey: {
      type: String,
      default: 'TableColumn'
    }
  },
  data() {
    return {
      tableColumn: [],
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      defaultChecked: [],
      sessionData: JSON.parse(sessionStorage.getItem(this.columnKey))
    }
  },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo
    }),
    authUserId() {
      return this.userInfo?.additional?.external[0]?.authUserId
    }
  },
  watch: {
    authUserId(val) {
      if (val && this.sessionData && this.sessionData[val]) {
        this.defaultChecked = filter(this.sessionData[val], 'checked').map(
          (v) => v.prop
        )
        this.tableColumn = this.sessionData[val]
        this.$emit('updateTableColumn', this.tableColumn)
      }
    }
  },
  created() {
    const tempData =
      (this.sessionData ? this.sessionData[this.authUserId] : '') ||
      this.defaultTableColumn
    this.defaultChecked = filter(tempData, 'checked').map((v) => v.prop)
    this.tableColumn = tempData
    this.$emit('updateTableColumn', this.tableColumn)
  },
  methods: {
    nodeCheck(node, checkedData) {
      this.tableColumn.forEach((v, i) => {
        if (v.prop === node.prop) {
          this.$set(this.tableColumn[i], 'checked', !node.checked)
        }
      })
      this.$emit('updateTableColumn', this.tableColumn)
      this.saveSession()
    },
    saveSession() {
      const val = this.sessionData || {}
      val[this.authUserId] = this.tableColumn
      sessionStorage.setItem(this.columnKey, JSON.stringify(val))
    }
  }
}
</script>
